﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NameReOrganizer
{
    class Program
    {
        static Random rnd = new Random();

        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: NameReOrganizer.exe <Path>");
            }
            else if (args.Length == 1)
            {
                string path = args[0];

                if (!Directory.Exists(path))
                {
                    Console.WriteLine("Directory does not exists.");
                }
                else
                {
                    NameReOrganize(path);
                }
            }

            Console.ReadKey();
            return;
        }

        private static void NameReOrganize(string path)
        {
            List<string> files = Directory.GetFiles(path).ToList<string>();
            string newPath = Path.GetFullPath(path + @"\..\" + Guid.NewGuid());

            Directory.CreateDirectory(newPath);

            int count = 0;

            while (files.Count > 0)
            {
                int rndNumber = rnd.Next(files.Count);
                
                string oldFileName = files[rndNumber];
                string newFileName = newPath + @"\" + GetGestureType(oldFileName) + "_" + count.ToString("D3") +".txt";

                File.Move(oldFileName, newFileName);
                files.RemoveAt(rndNumber);

                count++;
            }

            Directory.Delete(path);
            Directory.Move(newPath, path);

            Console.WriteLine("Processed files: " + count);
        }

        private static string GetGestureType(string filePath)
        {
            string result = "CorruptedGesture";

            if (!File.Exists(filePath))
            {
                throw new Exception("File not exists.");
            }

            using (TextReader reader = File.OpenText(filePath))
            {
                string line = "";

                while (!line.StartsWith("@"))
                {
                    line = reader.ReadLine();
                }

                result = line.Substring(1);

                reader.Close();
            }

            return result;
        }
    }
}
